package com.example.ch07.preferences;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.example.ch07.R;

/**
 * Entry into our redirection example, describing what will happen.
 */
public class SharedPreferencesActivity extends AppCompatActivity {

    private OnClickListener mClearListener = new OnClickListener() {
        public void onClick(View v) {
            // Erase the preferences and exit!
            SharedPreferences preferences = getSharedPreferences(
                    "RedirectData", 0);
            preferences.edit().remove("text").commit();
            finish();
        }
    };
    private OnClickListener mNewListener = new OnClickListener() {
        public void onClick(View v) {
            // Retrieve new text preferences.
            Intent intent = new Intent(SharedPreferencesActivity.this,
                    SharedPreferencesInputActivity.class);
            mStartForResult.launch(intent);
            ;
        }
    };
    private String mTextPref;
    private final ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == AppCompatActivity.RESULT_OK) {
                    loadPrefs();
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.c07_redirect_main);

        // Watch for button clicks.
        Button clearButton = (Button) findViewById(R.id.clear);
        clearButton.setOnClickListener(mClearListener);
        Button newButton = (Button) findViewById(R.id.newView);
        newButton.setOnClickListener(mNewListener);

        if (!loadPrefs()) {
            Intent intent = new Intent(this, SharedPreferencesInputActivity.class);
            mStartForResult.launch(intent);
        }
    }

    private final boolean loadPrefs() {
        // Retrieve the current redirect values.
        // NOTE: because this preference is shared between multiple
        // activities, you must be careful about when you read or write
        // it in order to keep from stepping on yourself.
        SharedPreferences preferences = getSharedPreferences("RedirectData", 0);

        mTextPref = preferences.getString("text", null);
        if (mTextPref != null) {
            TextView text = (TextView) findViewById(R.id.text);
            text.setText(mTextPref);
            return true;
        }

        return false;
    }
}
